import { KanaDataItem } from "@/utils/kanadata";
import { defineStore } from "pinia";
import { initStorage } from "./initStorage";

export const ALLOW_RANGE = "ALLOW_RANGE";
export const KANA_INDEX_RANGE = "KANA_INDEX_RANGE";
export const RIGHT_COUNT = "RIGHT_COUNT";

export const ERROR_COUNT = "ERROR_COUNT";

export interface AnswerStatistics {
	[key: string]: number;
}

export const useStore = defineStore({
	id: "app",
	state: () => ({
		kanaCount: 0,
		title: "假名记忆卡片系统",
		kanaIndexRange: [] as number[],
		kana: [] as Array<KanaDataItem>,
		rightCount: initStorage(RIGHT_COUNT, {}) as AnswerStatistics,
		errorCount: initStorage(RIGHT_COUNT, {}) as AnswerStatistics,
		allowRange: initStorage(ALLOW_RANGE, ["平假名", "片假名", "罗马字"]),
	}),
	actions: {
		setKana(val: Array<KanaDataItem>) {
			this.kana = val;
			this.kanaCount = val.length;
		},

		setAllowRange(val: string[]) {
			this.allowRange = val;
			window.localStorage.setItem(ALLOW_RANGE, JSON.stringify(val));
		},

		setKanaAllowIndex(val: number[]) {
			this.kanaIndexRange = val;
			window.localStorage.setItem(KANA_INDEX_RANGE, JSON.stringify(val));
		},

		addRightCount(val: number) {
			if (this.rightCount[val]) {
				this.rightCount[val]++;
			} else {
				this.rightCount[val] = 1;
			}
			window.localStorage.setItem(RIGHT_COUNT, JSON.stringify(this.rightCount));
		},

		addErrorCount(val: number) {
			if (this.errorCount[val]) {
				this.errorCount[val]++;
			} else {
				this.errorCount[val] = 1;
			}
			window.localStorage.setItem(ERROR_COUNT, JSON.stringify(this.errorCount));
		},

		clearRightCount() {
			this.rightCount = {};
			window.localStorage.setItem(RIGHT_COUNT, JSON.stringify(this.rightCount));
		},

		clearErrorCount() {
			this.errorCount = {};
			window.localStorage.setItem(ERROR_COUNT, JSON.stringify(this.errorCount));
		},
	},
	getters: {
		selectedKana(state) {
			return state.kana
				.filter((e) => e.isValid())
				.filter((e) => state.kanaIndexRange.includes(e.index));
		},
	},
});
